package service

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/vueadmin/app/admin/internal/dto"
	"github.com/vueadmin/app/admin/internal/model"
	"github.com/vueadmin/app/admin/internal/svc"
	"github.com/vueadmin/app/admin/internal/vo"
	"github.com/vueadmin/utils/conv"
	"gorm.io/gorm"
)

type adminuserService struct {
	svcCtx *svc.ServiceContext
}

func NewAdminuserService(svcCtx *svc.ServiceContext) *adminuserService {
	return &adminuserService{
		svcCtx: svcCtx,
	}
}

/**
 * @description(数据列表)
 * @buildcode(true)
*/
func (p adminuserService) GetPageList(req *dto.AdminuserPageReq) ([]*vo.AdminuserList, int64, error) {
	var (
		entity model.Adminuser
		list  []*vo.AdminuserList
		count int64
	)
	query := p.svcCtx.Db.Model(&entity)
	if !conv.IsEmpty(req.UserId) {
		query = query.Where("user_id = ?", req.UserId)
	}
	if !conv.IsEmpty(req.User) {
		query = query.Where("user = ?", req.User)
	}
	if !conv.IsEmpty(req.RoleId) {
		query = query.Where("role_id = ?", req.RoleId)
	}
	if !conv.IsEmpty(req.Status) {
		query = query.Where("status = ?", req.Status)
	}
	orderBy := "user_id desc"
	if !conv.IsEmpty(req.Sort) && !conv.IsEmpty(req.Order) {
		orderBy = fmt.Sprintf("%s %s", req.Sort, req.Order)
	}
	query = query.Preload("Role", func(db *gorm.DB) *gorm.DB {
		return db.Select("role_id,name")
	})
	query.Count(&count)
	if err := query.Limit(req.Limit).Offset((req.Page - 1) * req.Limit).Order(orderBy).Find(&list).Error; err != nil {
		return nil, 0, err
	}
	return list, count, nil
}

/**
 * @description(修改排序开关)
 * @buildcode(true)
*/
func (p adminuserService) UpdateExt(req map[string]interface{}) error {
	entity := model.Adminuser{}
	if err := p.svcCtx.Db.Model(&entity).Where("user_id",conv.Int(req["user_id"])).Updates(req).Error; err != nil {
		return err
	}
	return nil
}

/**
 * @description(添加)
 * @buildcode(true)
*/
func (p adminuserService) Add(req *dto.AdminuserAddReq) (int, error) {
	entity := model.Adminuser{}
	entity.Name = req.Name
	entity.User = req.User
	entity.Pwd = conv.EncryptPassword(req.Pwd)
	entity.RoleId = req.RoleId
	entity.Note = req.Note
	entity.Status = req.Status
	entity.CreateTime = conv.NowUnix()

	if err := p.svcCtx.Db.Create(&entity).Error; err != nil {
		return 0, err
	}
	return entity.UserId, nil
}

/**
 * @description(修改)
 * @buildcode(true)
*/
func (p adminuserService) Update(req *dto.AdminuserUpdateReq) error {
	entity := model.Adminuser{
		UserId: req.UserId,
	}
	query := p.svcCtx.Db
	if err := query.Limit(1).First(&entity).Error; err != nil {
		return err
	}
	entity.Name = req.Name
	entity.User = req.User
	entity.RoleId = req.RoleId
	entity.Note = req.Note
	entity.Status = req.Status
	entity.CreateTime = conv.UnixTime(req.CreateTime)

	field := conv.StringToSlice("name,user,role_id,note,status,create_time", ",")

	if err := query.Select(field).Updates(&entity).Error; err != nil {
		return err
	}
	return nil
}

/**
 * @description(获取修改详情)
 * @buildcode(true)
*/
func (p adminuserService) GetUpdateInfo(req *dto.AdminuserGetUpdateInfoReq) (*model.Adminuser, error) {
	entity := model.Adminuser{}
	if err := p.svcCtx.Db.Where("user_id = ?",req.UserId).Limit(1).First(&entity).Error; err != nil {
		return nil, err
	}
	return &entity, nil
}

/**
 * @description(删除)
 * @buildcode(false)
*/
func (p adminuserService) Delete(req *dto.AdminuserDeleteReq) error {
	if len(req.UserId) > 1 {
		return errors.New("禁止批量删除")
	}
	if req.UserId[0] == 1 {
		return errors.New("超级管理员禁止删除")
	}
	query := p.svcCtx.Db
	query = query.Where("user_id IN ?", req.UserId)
	if err := query.Delete(&model.Adminuser{}).Error; err != nil {
		return err
	}
	return nil
}

/**
 * @description(查看详情)
 * @buildcode(true)
*/
func (p adminuserService) Detail(req *dto.AdminuserDetailReq) (*vo.AdminuserDetail, error) {
	var info vo.AdminuserDetail
	query := p.svcCtx.Db.Model(&model.Adminuser{})
	if err := query.Where("user_id = ?",req.UserId).Limit(1).First(&info).Error; err != nil {
		return nil, err
	}
	return &info, nil
}

/**
 * @description(重置密码)
 * @buildcode(true)
*/
func (p adminuserService) ResetPwd(req *dto.AdminuserResetPwdReq) error {
	entity := model.Adminuser{
		UserId: conv.Int(req.UserId),
	}
	query := p.svcCtx.Db
	if err := query.Limit(1).First(&entity).Error; err != nil {
		return err
	}
	if err := query.Model(&entity).Update("pwd",conv.EncryptPassword(req.Pwd)).Error; err != nil {
		return err
	}
	return nil
}

/**
 * @description(查询sql下拉字段列表)
 * @buildcode(true)
*/
func (p adminuserService) GetFieldList(c *gin.Context) (map[string]interface{}, error) {
	var (
		RoleId []*vo.AdminuserRoleId
	)
	if err := p.svcCtx.Db.Raw(`select role_id,name from cd_role`).Scan(&RoleId).Error; err != nil {
		return nil, err
	}
	data := make(map[string]interface{})
	data["role_ids"] = RoleId
	return data, nil
}

